<template>
  <div class="task-tab-container task-card-tab">
    
    <!-- start 附加组件名称 快速定位 -->
    <!-- <div class="card-name-list">
      <span
        :class="{'active': activeTab == card.cardId }"
        v-for="(card, index) in taskCards"
        :key="index"
        @click="activeTab = card.cardId"
      >{{ card.cardName }}</span>
    </div> -->
    <!-- end 附加组件名称 快速定位 -->
    
    <!-- start 附加组件内容 -->
    <div class="card-info-list" ref="cardLists" v-loading="loading">
      
      <div class="card-info-container" v-for="card in taskCards" :key="card.cardId" v-show="isShowCardTab(card)" :id="card.cardId">
        
        <!-- start 连接器类型的附加组件 -->
        <template v-if="isConnectorCard(card)">
          
          <connector-card-warper
            :ref="`connector_${card.cardId}`"
            :customStateNameEnable="customStateNameEnable"
            :main-module-value="task"
            :card="card"
            :task="task"
            :bizId="taskId"
            :share-data="shareData"
            :visible="isShowCardTab(card)"
          />
          
        </template>
        <!-- end 连接器类型的附加组件 -->
        
        <!-- start 其他类型的附加组件 -->
        <template v-else>
          
          <!-- start 单次 -->
          <template v-if="card.inputType == 'single'">
            <single-card
              :ref="`singleCardRef_${card.cardId}`"
              :task="task"
              :customStateNameEnable="customStateNameEnable"
              :card="card"
              :share-data="shareData"
              :value="getCardValue(card.cardId)"
              :task-allow-update="initData.isAllowUpdate"
              :is-from-created="isFromCreated"
              v-bind="$attrs"
              @initData="getAttachData"
              v-on="$listeners"
              @loadingOpen="loadingOpen"
            />
          </template>
          <!-- end 单次 -->
          
          <!-- start 多次 -->
          <template v-else-if="card.inputType == 'multiple'">
            
            <!-- start 工时记录附加组件 -->
            <template v-if="card.specialfrom == '工时记录'">
              <hours-record-card
                :ref="`hoursRecordCard_${card.cardId}`"
                :customStateNameEnable="customStateNameEnable"
                :task="task"
                :card="card"
                :list-loading="loading"
                :share-data="shareData"
                :task-allow-update="initData.isAllowUpdate"
                v-on="$listeners"
                @loadingOpen="loadingOpen"
              />
            </template>
            <!-- end 工时记录附加组件 -->
            
            <!-- start 备件清单附加组件 -->
            <template v-else-if="card.specialfrom == '备件清单'">
              <spare-part-card
                :ref="`sparepartCardRef_${card.cardId}`"
                :share-data="shareData"
                :customStateNameEnable="customStateNameEnable"
                :task="task"
                :card="card"
                :list-loading="loading"
                :is-executor="shareData.isExecutor"
                :is-synergies="shareData.isSynergies"
                :task-allow-update="initData.isAllowUpdate"
              />
            </template>
            <!-- end 备件清单附加组件 -->
            
            <!-- start 服务清单附加组件 -->
            <template v-else-if="card.specialfrom == '服务清单'">
              <service-card
                :ref="`serviceCardRef_${card.cardId}`"
                :share-data="shareData"
                :customStateNameEnable="customStateNameEnable"
                :task="task"
                :card="card"
                :list-loading="loading"
                :task-allow-update="initData.isAllowUpdate"
              />
            </template>
            <!-- end 服务清单附加组件 -->
            
            <!-- start 物料申领附加组件 -->
            <template v-else-if="card.specialfrom == '物料申领'">
              <material-card
                :ref="`materialCardRef_${card.cardId}`"
                :task="task"
                :customStateNameEnable="customStateNameEnable"
                :list-loading="loading"
                :card="card"
                :login-user="loginUser"
                :warranty-status="warrantyStatus"
                :is-executor="shareData.isExecutor"
                :is-synergies="shareData.isSynergies"
                :task-allow-update="initData.isAllowUpdate"
              />
            </template>
            <!-- end 物料申领附加组件 -->
            
            <!-- start 其他多次附加组件 -->
            <template v-else>
              <multiple-card
                :ref="`isMultipleCard_${card.cardId}`"
                :task="task"
                :customStateNameEnable="customStateNameEnable"
                :card="card"
                :share-data="shareData"
                :list-loading="loading"
                :value="getCardValue(card.cardId)"
                :task-allow-update="initData.isAllowUpdate"
                :is-from-created="isFromCreated"
                @initData="getAttachData"
                v-on="$listeners"
                @loadingOpen="loadingOpen"
                @tabBarChangeItemNext="tabBarChangeItemNext"
                @addRow="addMultipleCardRow"
                @update="updateMultipleCardRow"
                @delete="deleteMultipleCardRow"
              />
            </template>
            <!-- end 其他多次附加组件 -->
            
          </template>
          <!-- end 多次 -->
          
        </template>
        <!-- end 其他类型的附加组件 -->
        
      </div>
    </div>
    <!-- end 附加组件内容 -->
  </div>
</template>

<script>
/* api */
import * as TaskApi from '@src/api/TaskApi.ts';
/* components */
import SingleCard from './components/SingleCard';
import MultipleCard from './components/MultipleCard';
import HoursRecordCard from './components/HoursRecordCard/HoursRecordCard.vue';
import SparepartCard from './components/SparepartCard/SparepartCard.vue';
import ServiceCard from './components/ServiceCard/ServiceCard.vue';
import MaterialCard from './components/MaterialCard/MaterialCard.vue'

import ConnectorCardWarper from './components/ConnectorCard.vue'
/* service */
import { isConnectorCard } from '@service/CardService';

/* util */
import i18n from '@src/locales';
import * as FormUtil from '@src/component/form/util';
import * as util from '@src/modules/task/util/task';
import { useFormTimezone, randomString } from 'pub-bbx-utils';
import { findComponentDownward } from "@src/util/assist";
const { disposeFormViewTime } = useFormTimezone();
export default {
  name: 'task-detail-card',
  inject: ['initData'],
  props: {
    shareData: {
      type: Object,
      default: () => ({})
    },
    rightActiveTab: {
      type: String,
      default: ''
    },
    taskCards: {
      type: Array,
      default: () => ([])
    },
    fromView: {
      type: String,
      default: ''
    },
    cardForms: {
      type: Array,
      default: () => ([])
    },
    customStateNameEnable: {
      type: Boolean,
      default: false
    }
  },
  inheritAttrs: false,
  data() {
    return {
      cardData: [],
      loading: true
    }
  },
  computed: {
    activeTab() {
      const defaultActiveTab = this.taskCards.length ? `add-on-${this.taskCards[0].cardId}` : ''
      return this.rightActiveTab || defaultActiveTab
    },
    /** 
    * @description 工单详情数据
    */
    task() {
      const taskType = this.initData.taskType;
      return Object.assign({}, this.shareData.task, { taskType });
    },
    taskId() {
      return this.task.id || '';
    },
    /** 
    * @description 附加组件数据(接口返回)
    */
    taskCardData() {
      return this.cardData;
    },
    /** 
    * @description 当前登录用户
    */
    loginUser() {
      return this.initData.loginUser
    },
    /** 
    * @description 质保状态
    */
    warrantyStatus() {
      return this.shareData?.warrantyStatus
    },
    // 新建工单入口来的
    isFromCreated() {
      return this.fromView === 'created';
    },
    /** 多次附加组件最大能添加的数量 */
    canAddTaskCardMaxNum() {
      return this.initData?.variationConfig?.maxTaskCardRow ?? 20;
    }
  },
  watch: {
    cardForms: {
      handler(val) {
        this.cardData = val;
      },
      immediate: true,
    }
  },
  methods: {
    isConnectorCard,
    /** 
    * @description 获取指定附加组件数据
    */
    getCardValue(cardId) {
      let cardInfo = this.taskCardData;
      return cardInfo.filter(card => card.cardId == cardId)[0];
    },
    loadingOpen(v){
      this.loading = v;
    },
    async getAttachData() {
      try {
        this.loadingOpen(true);
        const res = await TaskApi.getTaskCardInfoByTaskId({ taskId: this.task.id });
        this.cardData = res.result || [];
        this.$emit('dataUpdate', this.cardData)
      } catch (error) {
        console.warn('getAttachData -> error', error);
      } finally {
        this.loadingOpen(false);
      }
    },
    isShowCardTab(card) {
      return this.activeTab == `add-on-${card?.cardId}`
    },
    addMultipleCardRow(cardId, columns) {
      if(!this.cardData.filter(item => item.cardId === cardId)?.length) {
        this.cardData.push({
          inputType: 'multiple',
          cardId,
          attribute: [],
        })
      }

      const cardIndex = this.getMultipleCardIndex(cardId);
      const fields = columns;

      if(this.cardData[cardIndex]?.attribute?.length >= this.canAddTaskCardMaxNum) {
        return this.$message.warning(i18n.t('task.tip.multipleCardNumTip',{ max: this.canAddTaskCardMaxNum }));
      }
      
      let form = {};
      form = util.packToForm(fields, disposeFormViewTime(fields, form));
      form = FormUtil.initialize(fields, form);
      form.id = randomString();
      form.operateType = 'save';

      this.cardData[cardIndex].attribute.unshift(form);
    },
    /** 
    * @description 多次附加组件列表修改数据
    */
    updateMultipleCardRow({ fieldName, newValue, index, updateRow = false }, cardId) {
      const cardIndex = this.getMultipleCardIndex(cardId);
      
      // 更新单行数据
      if(updateRow) {
        return this.$set(this.cardData[cardIndex].attribute, index, newValue);
      }

      if(this.cardData[cardIndex].attribute[index].operateType !== 'save') {
        this.$set(this.cardData[cardIndex].attribute[index], 'operateType', 'edit');
      }
      this.$set(this.cardData[cardIndex].attribute[index], fieldName, newValue);
    },
    deleteMultipleCardRow(row, index, cardId) {
      const cardIndex = this.getMultipleCardIndex(cardId);
      const rowIndex = this.cardData[cardIndex].attribute.findIndex(item => item.id === row.id);
      if(row.operateType === 'save') {
        this.cardData[cardIndex].attribute.splice(rowIndex, 1);
      } else {
        this.$set(this.cardData[cardIndex].attribute[rowIndex], 'operateType', 'delete');
      }
    },
    tabBarChangeItemNext(next) {
      this.$emit('tabBarChangeItemNext', next);
    },
    checkMultipleCardDataChange(previous, next) {
      if(this.$refs[`isMultipleCard_${previous.cardId}`]?.length) {
        this.$refs[`isMultipleCard_${previous.cardId}`][0].checkMultipleCardDataChange(previous, next);
      } else {
        this.tabBarChangeItemNext(next);
      }
    },  
    getMultipleCardIndex(cardId) {
      return this.cardData.findIndex(item => item.cardId === cardId);
    },
    // 默认打开添加附加组件的弹窗
    openAddonsDialog(card) {
      if(this.isConnectorCard(card)) {
        const formConnectorCardComponent = findComponentDownward(this.$refs[`connector_${card.cardId}`]?.[0], 'connector-module-connector-card-multi') || {};
        return formConnectorCardComponent?.openAddonsDialogAuto();
      }
      if(card.inputType === 'multiple') {
        // const附加组件的ref
        const AddonsName = {
          '工时记录': `hoursRecordCard_${card.cardId}`,
          '备件清单': `sparepartCardRef_${card.cardId}`,
          '服务清单': `serviceCardRef_${card.cardId}`,
          '物料申领': `materialCardRef_${card.cardId}`
        }
        const refName = AddonsName?.[card.specialfrom] ?? `isMultipleCard_${card.cardId}` ?? ''
        this.$refs[refName]?.[0]?.openAddonsDialogAuto()
      }else if(card.inputType === 'single'){
        this.$refs[`singleCardRef_${card.cardId}`]?.[0]?.openAddonsDialogAuto()
      }
    },
  },
  mounted() {
    if(this.isFromCreated) {
      this.loading = false;
    } else {
      this.getAttachData();
    }
  },
  components: {
    [SingleCard.name]: SingleCard,
    [MultipleCard.name]: MultipleCard,
    [ServiceCard.name]: ServiceCard,
    [SparepartCard.name]: SparepartCard,
    [HoursRecordCard.name]: HoursRecordCard,
    [MaterialCard.name]: MaterialCard,
    [ConnectorCardWarper.name]: ConnectorCardWarper,
  }
}
</script>

<style lang="scss">
.task-card-tab {
  height: 100%;
  padding: 0 !important;
  overflow: hidden;

  display: flex;
  flex-direction: column;

  // 附加组件名称
  .card-name-list {
    padding: 12px 16px 4px;
    border-bottom: 1px solid $color-border-l2;

    span {
      margin: 0 12px 8px 0;
      padding: 6px 12px;
      color: $text-color-regular;
      font-size: $font-size-small;
      background-color: $bg-color-l1;
      border-radius: 16px;
      display: inline-block;

      &:hover,
      &.active {
        background-color: $color-primary-light-1;
        cursor: pointer;
      }
    }
  }

  // 附加组件内容
  .card-info-list {
    flex: 1;
    overflow: auto;

    .card-info-container {
      padding: 16px;

      .btn-group {
        padding: 10px 0;
        padding-left: 12px;
      }
    }
  }
}
</style>
